package tech.shupi.babytapmobile

import android.util.Log
import com.facebook.react.bridge.Promise
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactContextBaseJavaModule
import com.facebook.react.bridge.ReactMethod
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject
import java.io.File
import java.io.IOException
import java.net.URLEncoder
import java.util.concurrent.TimeUnit
import java.util.Base64

class DouBaoTTSModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) {

    companion object {
        const val NAME = "DouBaoTTSModule"
        private const val TAG = "DouBaoTTS"
        private const val HOST = "openspeech.bytedance.com"
        private const val API_URL = "https://$HOST/api/v1/tts"
    }

    private var client: OkHttpClient? = null
    private var appid: String = ""
    private var token: String = ""
    private var isInitialized: Boolean = false

    override fun getName(): String = NAME

    @ReactMethod
    fun initializeTTS(promise: Promise) {
        try {
            client = OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .build()
            
            isInitialized = true
            promise.resolve(true)
            Log.d(TAG, "豆包TTS初始化成功")
            
        } catch (e: Exception) {
            Log.e(TAG, "豆包TTS初始化失败", e)
            promise.reject("INIT_ERROR", "豆包TTS初始化失败: ${e.message}")
        }
    }

    @ReactMethod
    fun synthesizeAudio(text: String, voice: String, outputPath: String, promise: Promise) {
        if (!isInitialized) {
            promise.reject("NOT_INITIALIZED", "TTS未初始化")
            return
        }

        if (appid.isEmpty() || token.isEmpty()) {
            promise.reject("NO_CONFIG", "TTS配置未设置，请在设置中配置appid和token")
            return
        }

        try {
            // 构建请求参数
            val requestBody = buildRequestBody(text, voice)
            
            // 构建请求
            val request = Request.Builder()
                .url(API_URL)
                .addHeader("Authorization", "Bearer; $token")
                .post(requestBody)
                .build()

            // 发送请求
            client?.newCall(request)?.enqueue(object : okhttp3.Callback {
                override fun onFailure(call: Call, e: IOException) {
                    Log.e(TAG, "TTS请求失败", e)
                    promise.reject("REQUEST_ERROR", "TTS请求失败: ${e.message}")
                }

                override fun onResponse(call: Call, response: Response) {
                    try {
                        val responseBody = response.body?.string()
                        Log.d(TAG, "TTS响应: $responseBody")
                        
                        if (response.isSuccessful && responseBody != null) {
                            val jsonResponse = JSONObject(responseBody)
                            
                            // 检查是否成功
                            val code = jsonResponse.optInt("code", -1)
                            if (code == 3000 && jsonResponse.has("data")) {
                                val audioBase64 = jsonResponse.getString("data")
                                
                                // 保存音频文件
                                val success = saveAudioFile(audioBase64, outputPath)
                                if (success) {
                                    promise.resolve(outputPath)
                                    Log.d(TAG, "音频文件保存成功: $outputPath")
                                } else {
                                    promise.reject("SAVE_ERROR", "音频文件保存失败")
                                }
                            } else {
                                val errorMsg = jsonResponse.optString("message", "未知错误")
                                promise.reject("TTS_ERROR", "语音合成失败: $errorMsg")
                            }
                        } else {
                            promise.reject("HTTP_ERROR", "HTTP错误: ${response.code}")
                        }
                    } catch (e: Exception) {
                        Log.e(TAG, "解析响应失败", e)
                        promise.reject("PARSE_ERROR", "解析响应失败: ${e.message}")
                    }
                }
            })
            
        } catch (e: Exception) {
            Log.e(TAG, "语音合成失败", e)
            promise.reject("SPEAK_ERROR", "语音合成失败: ${e.message}")
        }
    }

    private fun buildRequestBody(text: String, voice: String): RequestBody {
        val jsonObject = JSONObject().apply {
            // App 部分
            put("app", JSONObject().apply {
                put("appid", appid)
                put("token", token)
                put("cluster", "volcano_tts")
            })
            
            // User 部分
            put("user", JSONObject().apply {
                put("uid", "uid123")
            })
            
            // Audio 部分
            put("audio", JSONObject().apply {
                put("voice_type", "BV700_streaming")
                put("encoding", "mp3")
                put("compression_rate", 1)
                put("rate", 24000)
                put("speed_ratio", 1.0)
                put("volume_ratio", 1.0)
                put("pitch_ratio", 1.0)
                put("emotion", "happy")
                put("language", "cn")
            })
            
            // Request 部分
            put("request", JSONObject().apply {
                put("reqid", java.util.UUID.randomUUID().toString())
                put("text", text)
                put("text_type", "plain")
                put("operation", "query")
                put("silence_duration", "125")
                put("with_frontend", "1")
                put("frontend_type", "unitTson")
                put("pure_english_opt", "1")
                put("extra_param", JSONObject().apply {
                    put("disable_emoji_filter", true)
                }.toString())
            })
        }
        
        return jsonObject.toString().toRequestBody("application/json; charset=utf-8".toMediaType())
    }

    private fun saveAudioFile(audioBase64: String, outputPath: String): Boolean {
        return try {
            val audioData = Base64.getDecoder().decode(audioBase64)
            
            // 使用与服务器相同的外部存储目录
            val externalDir = reactApplicationContext.getExternalFilesDir(null)
            val golangDataDir = File(externalDir, "golang_data")
            val cardsDir = File(golangDataDir, "cards")
            if (!cardsDir.exists()) {
                cardsDir.mkdirs()
            }
            
            val fileName = outputPath.substring(outputPath.lastIndexOf('/') + 1)
            val file = File(cardsDir, fileName)
            
            file.writeBytes(audioData)
            Log.d(TAG, "音频文件保存成功: ${file.absolutePath}")
            true
        } catch (e: Exception) {
            Log.e(TAG, "保存音频文件失败", e)
            false
        }
    }

    @ReactMethod
    fun isInitialized(promise: Promise) {
        promise.resolve(isInitialized)
    }

    @ReactMethod
    fun setTTSConfig(appId: String, ttsToken: String, promise: Promise) {
        try {
            this.appid = appId
            this.token = ttsToken
            Log.d(TAG, "TTS配置已更新: appid=$appid, token=${token.take(10)}...")
            promise.resolve(true)
        } catch (e: Exception) {
            Log.e(TAG, "设置TTS配置失败", e)
            promise.reject("CONFIG_ERROR", "设置TTS配置失败: ${e.message}")
        }
    }

    @ReactMethod
    fun getTTSConfig(promise: Promise) {
        try {
            val config = JSONObject().apply {
                put("appid", appid)
                put("token", token)
            }
            promise.resolve(config.toString())
        } catch (e: Exception) {
            Log.e(TAG, "获取TTS配置失败", e)
            promise.reject("CONFIG_ERROR", "获取TTS配置失败: ${e.message}")
        }
    }

    @ReactMethod
    fun destroyTTS(promise: Promise) {
        try {
            client?.dispatcher?.executorService?.shutdown()
            client?.connectionPool?.evictAll()
            client = null
            isInitialized = false
            promise.resolve(true)
            Log.d(TAG, "销毁豆包TTS")
        } catch (e: Exception) {
            Log.e(TAG, "销毁豆包TTS失败", e)
            promise.reject("DESTROY_ERROR", "销毁豆包TTS失败: ${e.message}")
        }
    }

    override fun onCatalystInstanceDestroy() {
        super.onCatalystInstanceDestroy()
        try {
            client?.dispatcher?.executorService?.shutdown()
            client?.connectionPool?.evictAll()
            client = null
            isInitialized = false
        } catch (e: Exception) {
            Log.e(TAG, "销毁豆包TTS失败", e)
        }
    }
} 